<script setup>

import mqtt from 'mqtt'
import api from './api.js'
import TitleLabel from "@/components/TitleLabel.vue";
import dateUtil from '@/utils/date.js'

const { proxy } = getCurrentInstance();
const { asset_state } = proxy.useDict("asset_state");


const tableRef = ref();

const openFlag = ref(false);
const messageList = ref([]);
const deviceList = ref([]);
const assetList = ref([]);
const assetTableRef = ref();

const emit = defineEmits(['sub']);


let host = window.location.hostname;

let client;


function showImg(img) {
  return import.meta.env.VITE_APP_BASE_API + img;
}

function findExistMsg(msg) {
  return messageList.value.find(item=> {
    return item.tag === msg;
  });
}

function insertIntoMessageList(msg) {
  let existMsg = findExistMsg(msg);
  if (existMsg) {
    existMsg.time = new Date();
  } else {
    messageList.value.splice(0, 0, {
      tag: msg,
      time: new Date()
    });
  }
}

function pushInAssetList(asset) {
  const list = assetList.value;
  if (list.find(item=>item.rfid === asset.rfid)) {
    return;
  }
  list.push(asset);
}

function getAssetByRfid(tag) {
  api.getAssetByRfid(tag).then((res)=> {
    if (res && res.length) {
      for(let i = 0;i<res.length;i++) {
        const asset = res[i];
        pushInAssetList(asset);
      }

    }

  });
}

function createWebsocket() {
  client = mqtt.connect(`tcp://${host}:61614`);
  client.on('connect', function () {
    console.log('已连接到 MQTT Broker');
  });

  client.on('message', function (topic, message) {
    const msg = message.toString();
    console.log(`收到消息: ${msg} 来自主题: ${topic}`);
    insertIntoMessageList(msg);
    getAssetByRfid(msg);
  });

  client.on('error', function (err) {
    console.error('错误:', err);
  });

  client.on('close', function () {
    console.log('关闭mqtt连接');
  })

  client.on('end', function () {
    console.log('End mqtt连接');
  })
}


let lastUuid = null;

/**
 * 订阅mqtt主题
 * @param uuid
 */
function subscribe(uuid) {
  // 订阅主题前，把上次的主题订阅取消掉
  unsubscribeLast();
  const topic = `device/${uuid}/tag`;
  client.subscribe(topic, { qos: 1 }, function (err, granted) {
    if (!err) {
      console.log(`${uuid}已成功订阅`);
    }
  });
}

/**
 * 取消订阅mqtt主题
 * @param uuid
 */
function unsubscribe(uuid) {
  if (lastUuid) {
    client.unsubscribe(`device/${uuid}/tag`);
  }
}

function unsubscribeLast() {
  if (lastUuid) {
    unsubscribe(lastUuid);
  }
}

function deviceRead(device) {
  deviceList.value.forEach(item=> {
    item.running = false;
  })
  const uuid = device.number;
  device.running = true;
  subscribe(uuid);
  // 发送盘点请求
  startInventory(uuid);
  lastUuid = uuid;
}

function deviceStopRead(device) {
  const uuid = device.number;
  device.running = false;
  // 去掉消息订阅
  unsubscribe(uuid);
  // 发送盘点请求
  stopInventory(uuid);
  lastUuid = null;
}

function closeWebsocket() {
  if (client) {
    client.end();
  }
}

function startInventory(uuid) {
  api.inventory(uuid).then(response => {
    proxy.$modal.msgSuccess("RFID读取");
  })
}

function stopInventory(uuid) {
  api.stopInventory(uuid).then(response => {
    proxy.$modal.msgSuccess("停止RFID读取");
  })
}

function stopLastInventory() {
  if (lastUuid) {
    stopInventory(lastUuid);
  }
}

function sub() {
  const current = tableRef.value.getCurrentRecord();
  const records = assetTableRef.value.getCheckboxRecords(true);
  emit('sub', records);
  close();
}

async function getDeviceList() {
  const l = await api.list();
  if (l.length > 0) {
    l[0].selected = true;
  }
  deviceList.value = l;
  return deviceList;
}

function open() {
  // 创建WebSocket监听RFID的读取
  openFlag.value = true;
  messageList.value = [];
  createWebsocket();
  getDeviceList();

}

function close() {
  openFlag.value = false;
}

function onClose() {
  stopLastInventory();
  closeWebsocket();
}

// 外部使用的属性或方法
defineExpose({
  open
})
</script>

<template>

  <div>
    <el-dialog width="70%" title="RFID读卡" v-model="openFlag" align-center top="50" @close="onClose">

      <div class="rfid-section">
        <div class="left">
          <title-label>用户设备</title-label>
          <vxe-table ref="tableRef" :data="deviceList" height="150" :row-config="{isHover: true}">
            <vxe-column title="运行灯">
              <template #default="{ row }">
                <span class="breath-light" :class="{'active': row.running}"></span>
              </template>
            </vxe-column>
            <vxe-column field="name" title="设备名称"></vxe-column>
            <vxe-column field="time" title="时间">
              <template #default="{ row }">
                <el-button v-if="!row.running" size="small" @click="deviceRead(row)">读取</el-button>
                <el-button v-else size="small" @click="deviceStopRead(row)">停止</el-button>
              </template>
            </vxe-column>
          </vxe-table>

        </div>
        <div class="right">
          <title-label>读取到的标签</title-label>
          <vxe-table ref="tableRef" :data="messageList" height="150" :row-config="{isCurrent: true, isHover: true}">
            <vxe-column field="tag" title="标签"></vxe-column>
            <vxe-column field="time" title="时间">
              <template #default="{ row }">
                {{dateUtil.formatDate(row.time)}}
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </div>
      <div class="asset-section">
        <title-label>读取到的资产</title-label>
        <vxe-table height="250" ref="assetTableRef" :data="assetList">
          <vxe-column type="seq" width="55" align="center" />
          <vxe-column type="checkbox" width="55" align="center" />
          <vxe-column field="state" width="80" title="状态" align="center">
            <template #default="{ row }">
              <dict-tag :options="asset_state" :value="row.state" />
            </template>
          </vxe-column>
          <vxe-column field="number" width="120" title="图片" align="center">
            <template #default="{ row }">
              <el-tooltip v-if="row.imgUrl" class="box-item" effect="dark" placement="right-start">
                <template #content>
                  <img alt="" :src="showImg(row.imgUrl)" width="100" height="100" />
                </template>
                <img alt="" :src="showImg(row.imgUrl)" width="30" height="30" />
              </el-tooltip>
              <span v-else>没有图片</span>
            </template>
          </vxe-column>
          <vxe-column field="number" width="120" title="资产编码" align="center"/>
          <vxe-column field="name" width="180" title="资产名称" align="center"/>
          <vxe-column field="categoryName" width="120" title="资产分类" align="center"/>
          <vxe-column field="rfid" width="290" title="RFID" align="center"/>
          <vxe-column field="brand" width="120" title="品牌" align="center"/>
          <vxe-column field="model" width="120" title="型号" align="center"/>
          <vxe-column field="buyWay" width="120" title="购置方式" align="center"/>
          <vxe-column field="buyTime" width="180" title="购置时间" align="center">
            <template #default="{ row }">
              <span>{{ row.buyTime }}</span>
            </template>
          </vxe-column>
          <vxe-column field="buyPrice" width="120" title="购置金额" align="center"/>
          <vxe-column field="userName" width="120" title="使用人" align="center"/>
          <vxe-column field="adminName" width="120" title="管理员" align="center"/>
        </vxe-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-row type="flex" justify="end">
          <el-button @click="sub">确定</el-button>
          <el-button @click="close">取消</el-button>
        </el-row>
      </div>
    </el-dialog>
  </div>


</template>

<style scoped lang="scss">
.device-list {
  display: flex;
  width: 100%;
  .content {
    flex-grow: 1;
  }
  .buttons {
    flex-shrink: 0;
  }
}

.rfid-section {
  display: flex;
  width: 100%;
  .left {
    width: 50%;
    padding: 15px;
  }
  .right {
    width: 50%;
    padding: 15px;
  }
}

.asset-section {

}
</style>